import java.util.List;

import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;


public class CFGBuilder {
	
	private CompilationUnit unit;
	
	public CFG build(char[] source, String methodName){
		ASTParser parser = ASTParser.newParser(AST.JLS3);  
		parser.setSource(source);
		unit = (CompilationUnit) parser.createAST(null);
		unit.recordModifications();
		MethodDeclaration method = getMethod(methodName);
		CFG cfg = CFG.buildCFG(method);
		return cfg;
	}
	
	@SuppressWarnings("unchecked")
	public MethodDeclaration getMethod(String methodName){
		List<ASTNode> types = unit.types();
			for (ASTNode node : types) {
				if(node.getNodeType() == ASTNode.TYPE_DECLARATION){
					TypeDeclaration td = (TypeDeclaration) node;
					MethodDeclaration[] methods = td.getMethods();
					for (MethodDeclaration method : methods) {
						if (method.getName().toString().equalsIgnoreCase(methodName))
							return method;
					}
				}
			}
		return null;	
	}
}
